package cn.epsilon3.media.ses.tencent.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.epsilon3.configBean.InitializingTencentSesConfig;
import cn.epsilon3.exception.Epsilon3Exception;
import cn.epsilon3.media.ses.tencent.service.TencentSesNormalClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.SendEmailResponse;
import com.tencentcloudapi.ses.v20201002.models.Template;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 腾讯云邮件服务器
 *
 * @author epsilon3
 * @date 2023-05-14
 */
@Service
public class TencentSesNormalClientImpl implements TencentSesNormalClient {

    private static final Log log = LogFactory.get();

    @Resource
    InitializingTencentSesConfig initializingTencentSesConfig;

    @Override
    public SendEmailResponse sendMail(String[] emails,
                                      JSONObject sendParam,
                                      String subject) {
        SendEmailResponse sendEmailResponse = null;
        if (ObjectUtil.isNotNull(initializingTencentSesConfig.getEnable()) && initializingTencentSesConfig.getEnable()) {
            Credential cred = new Credential(initializingTencentSesConfig.getSecretId(),
                    initializingTencentSesConfig.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SesClient client = new SesClient(cred, initializingTencentSesConfig.getRegion(), clientProfile);
            SendEmailRequest req = new SendEmailRequest();
            req.setFromEmailAddress(initializingTencentSesConfig.getEmailAddress());
            ;
            req.setDestination(emails);
            Template template1 = new Template();
            template1.setTemplateID(initializingTencentSesConfig.getTemplateID());
            template1.setTemplateData(sendParam.toJSONString());
            req.setTemplate(template1);
            req.setSubject(subject);
            log.info(JSON.toJSONString(req));
            try {
                sendEmailResponse = client.SendEmail(req);
                return sendEmailResponse;
            } catch (TencentCloudSDKException tencentCloudSDKException) {
                throw new Epsilon3Exception("tencent ses send exception：" + tencentCloudSDKException.getMessage());
            }
        }
        return null;
    }


}
